package com.company.project.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Component
public class FileUploadUtil {

    @Value("${file.imgStaticPath}")
    private String imgStaticPath;

    @Value("${file.imguploadFolder}")
    private String imguploadFolder;

    @Value("${file.videoStaticPath}")
    private String videoStaticPath;

    @Value("${file.videouploadFolder}")
    private String videouploadFolder;

    @Value("${file.otherStaticPath}")
    private String otherStaticPath;

    @Value("${file.otheruploadFolder}")
    private String otheruploadFolder;

    public String writeFile(MultipartFile file,String fileType){
        String filePath = null;
        String filePathResult = null;
        if(file.isEmpty()){
            return null;
        }
        if(("img").equals(fileType)){
            filePath = imguploadFolder;
            filePathResult = imgStaticPath;
        }
        if(("video").equals(fileType)){
            filePath = videouploadFolder;
            filePathResult = videoStaticPath;
        }
        if(("other").equals(fileType)){
            filePath = otheruploadFolder;
            filePathResult = otherStaticPath;
        }
        if(filePath==null || filePathResult==null){
            return null;
        }
        String suffixName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String fileName = UUID.randomUUID()+suffixName;
        File dest = new File(filePath+fileName);
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

        return filePathResult+fileName;
    }
}
